import {
	clearRead
} from '/common/api';
class WebSocket {

	constructor() {
		let myInfo = uni.getStorageSync('myInfo')

		this.userId = '';
		this.reconnectTimer = null; // 添加一个属性来保存重连定时器

		if (myInfo != '') {
			let my = JSON.parse(myInfo);
			this.userId = my.id;
			this.connect(this.userId);
		}
	}

	/**
	 * 连接
	 */
	connect(userId) {
		const that = this; // 保存对当前实例的引用

		const audio = uni.createInnerAudioContext();
		audio.src = "/static/Ringtones-mp3/skype.mp3"
		uni.connectSocket({
			url: 'ws://192.168.254.133:80/api/xuanliao-ws?userId=' + userId,
			// url: 'ws://xuanhao.free.idcfengye.com/api/xuanliao-ws?userId=' + userId,
			success(res) {
				console.log("socket连接成功！");
			},
			fail() {
				console.log("socket连接失败！");
				that.scheduleReconnect(); // 连接失败时，安排重连
			}
		})

		uni.onSocketOpen(res => {
			console.log("监测到已连接上websocket")
			clearTimeout(that.reconnectTimer); // 清除重连定时器
		})

		uni.onSocketMessage((res) => {
			if (res) {
				audio.play();
				let data = JSON.parse(res.data);
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				if (data.type === 'msg_send') {
					if (currentPage.$page.route === 'subpkg/chat_interface/chat_interface') {
						currentPage.getAddMsgList();
						clearRead({
							userId: userId,
							cId: data.cid
						})
					}
					if (currentPage.$page.route === 'pages/message/message') {
						currentPage.Refreash();
					}
				}
				if(data.type === 'friend_request'){
					if (currentPage.$page.route === 'pages/friend/friend') {
						currentPage.Init();
					}
					if (currentPage.$page.route === 'subpkg/friend_request/friend_request') {
						currentPage.Init();
					}
				}
			}
		});

		uni.onSocketError(res => {
			console.log("监测到连接websocket错误")
			that.scheduleReconnect(); // 连接出错时，安排重连
		})

		uni.onSocketClose(res => {
			console.log("监测到连接websocket已关闭")
			that.scheduleReconnect(); // 连接关闭时，安排重连
		})
	}

	// 重连方法
	scheduleReconnect() {
		if (this.reconnectTimer === null) {
			this.reconnectTimer = setTimeout(() => {
				this.connect(this.userId); // 递归调用connect方法进行重连
			}, 60000); // 60秒后重试
		}
	}

}

export default new WebSocket();